package cn.springcloud.alibaba.gateway.handler;

import cn.springcloud.alibaba.core.constant.Constant;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.util.FastByteArrayOutputStream;
import reactor.core.publisher.Mono;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CaptchaHandler implements HandlerFunction<ServerResponse> {

	private static final String JPEG = "jpeg";

	@Autowired
	private Producer producer;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {
		//生成验证码
		String capText = producer.createText();
		BufferedImage image = producer.createImage(capText);
		//保存验证码信息
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String key = Constant.CAPTCHA_KEY + ":" + uuid;
		stringRedisTemplate.opsForValue().set(key, capText, 3, TimeUnit.MINUTES);

		log.info("key:{}, capText:{}", key, capText);

		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try {
			ImageIO.write(image, JPEG, os);
		} catch (IOException e) {
			log.error("ImageIO write err", e);
			return Mono.error(e);
		}

		return ServerResponse
			.status(HttpStatus.OK)
			.contentType(MediaType.IMAGE_JPEG)
			.header(Constant.CAPTCHA_UUID, uuid)
			.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
	}
}
